<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="岗位" prop="postId">
                <el-select
                    v-if="$store.getters.allDefectObj['HR-WEB-077'] == 1"
                    v-model="queryParams.postId"
                    placeholder="请选择岗位"
                >
                    <el-option
                        v-for="item in showPostList"
                        :key="item.postId"
                        :label="item.postName"
                        :value="item.postId"
                    ></el-option>
                </el-select>
                <el-input v-else v-model="queryParams.postName"></el-input>
            </el-form-item>

            <el-form-item label="创建时间" prop="daterange">
                <el-date-picker
                    v-model="timeArr"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="setChangeDate($event, 'startDate', 'endDate')"
                >
                </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['back:leave:add']"
                        >新建</el-button
                    >
                </el-col>
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="leaveList"
                @selection-change="handleSelectionChange"
            >
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column label="主键" align="center" prop="id" /> -->
                <el-table-column
                    type="index"
                    label="序号"
                    width="55"
                    align="center"
                />

                <el-table-column label="岗位" align="center" prop="postName">
                </el-table-column>

                <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                    width="180"
                >
                    <template slot-scope="scope">
                        <span>{{
                            parseTime(scope.row.createTime, "{y}-{m}-{d}")
                        }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="创建人"
                    align="center"
                    prop="createName"
                />
                <el-table-column
                    v-if="$store.getters.allDefectObj['HR-WEB-075'] == 1"
                    label="计费标准"
                    align="center"
                    prop="postSalary"
                >
                    <template slot-scope="scope">
                        <span>{{ scope.row.postSalary }}元/小时</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                    label="扣款工资(时薪)"
                    align="center"
                    prop="lossSalary"
                >
                    <template slot-scope="scope">
                        <span>{{ scope.row.lossSalary }}元/小时</span>
                    </template>
                </el-table-column> -->
                <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['back:leave:edit']"
                            >修改</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['back:leave:edit']"
                            >删除</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleRead(scope.row)"
                            v-hasPermi="['back:leave:edit']"
                            >查看</el-button
                        >
                        <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['back:leave:remove']"
                >删除</el-button
              > -->
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="total > 10"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改【请填写功能名称】对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-form-item label="岗位" prop="postId">
                        <el-select
                            v-model="form.postId"
                            @change="setPostName"
                            :disabled="showOptions || form.id"
                            placeholder="请选择岗位"
                        >
                            <el-option
                                v-for="item in postList"
                                :key="item.postId"
                                :label="item.postName"
                                :value="item.postId"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="计费标准" prop="postSalary">
                        <el-input
                            v-model="form.postSalary"
                            placeholder="请输入计费标准"
                            :disabled="showOptions"
                        />
                    </el-form-item>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button
                    type="primary"
                    @click="submitForm"
                    v-show="!showOptions"
                    >保存</el-button
                >
                <el-button v-if="!showOptions" @click="cancel">取 消</el-button>
                <el-button v-else @click="cancel">返 回</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getSalaryList,
    updateSalary,
    deleteSalary,
    addSalary,
    getSalaryListByUserId,
} from "@/api/hrm/scalaryManager";

import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listPostAll } from "@/api/system/post";
export default {
    name: "SalaryManager",
    dicts: ["sys_user_sex"],
    data() {
        return {
            showPostList:[], 
            // 职位选项
            postList: [],
            // 部门树选项
            deptOptions: [],
            deptOptionsArray: null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 【请填写功能名称】表格数据
            leaveList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                startDate: null,
                endDate: null,
                postName: null,
                postId: " ",
                pageNum: 1,
                pageSize: 10,
                orderByColumn: "createTime",
                isAsc: "descending",
                realName: null,
                sex: null,
                staffType: null,
                userId: null,
                deptId: null,
                orgId: null,

                type: 1,
                toTime: null,
                timeVal: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                postSalary: [
                    {
                        required: true,
                        message: "计费标准不能为空",
                        trigger: "blur",
                    },
                    //正整数
                    {
                        pattern: /^[1-9]\d*$/,
                        message: "计费标准必须为正整数",
                        trigger: "blur",
                    },
                ],
                lossSalary: [
                    {
                        required: true,
                        message: "计费标准不能为空",
                        trigger: "blur",
                    },
                    //正整数
                    {
                        pattern: /^[1-9]\d*$/,
                        message: "计费标准必须为正整数",
                        trigger: "blur",
                    },
                ],
                realName: [
                    {
                        required: true,
                        message: "姓名不能为空",
                        trigger: "change",
                    },
                ],
                userId: [
                    {
                        required: true,
                        message: "用户ID不能为空",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "部门ID不能为空",
                        trigger: "blur",
                    },
                ],
                orgId: [
                    {
                        required: true,
                        message: "所属部门不能为空",
                        trigger: "blur",
                    },
                ],
                postId: [
                    {
                        required: true,
                        message: "所属岗位的ID字符串不能为空",
                        trigger: "blur",
                    },
                ],
                type: [
                    {
                        required: true,
                        message: "0:加班，1：加班不能为空",
                        trigger: "change",
                    },
                ],
                toTime: [
                    {
                        required: true,
                        message: "加班或者加班的日期不能为空",
                        trigger: "blur",
                    },
                ],
                timeVal: [
                    {
                        required: true,
                        message: "加班或者加班的时间按小时算不能为空",
                        trigger: "blur",
                    },
                    //正整数
                    {
                        pattern: /^[1-9]\d*$/,
                        message: "加班的日期必须为正整数",
                        trigger: "blur",
                    },
                ],
            },

            showTableVision: false,
            showOptions: false,

            //时间段
            timeArr: [],
        };
    },
    components: { Treeselect },
    created() {
        this.getList();
        this.getTreeselect();
        this.getPostList();
    },
    methods: {
        setChangeDate(item, startDate, endDate) {
            console.log(item, "时间段");
            if (item.length > 0) {
                this.queryParams.startDate = item[0];
                this.queryParams.endDate = item[1];
            } else {
                this.queryParams.startDate = null;
                this.queryParams.endDate = null;
            }
        },
        setPostName(value) {
            let temp = this.postList.find((obj) => obj.postId == value);

            if (temp && temp.postName) {
                this.form.postName = temp.postName;
            }
        },
        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let nameArr = [];
                let selIds = ids.split(",");
                this.postList.forEach((item) => {
                    selIds.forEach((sel) => {
                        if (item.postId == sel) {
                            nameArr.push(item.postName);
                        }
                    });
                });
                if (nameArr.length <= 0) {
                    return "—";
                }
                return nameArr.join(",");
            }
        },
        getPostList() {
            listPostAll().then((res) => {
                this.showPostList =[...res.data];
                this.postList = res.data;
                this.showPostList.push({ postId: " ", postName: "全部岗位" });
            });
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsArray = this.flattenArray(this.deptOptions);
            });
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },
        parseSelectTree(id) {
            console.log(this.deptOptionsArray, "this.deptOptionsArray");
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        setFormBase(row) {
            let temp = { ...row };
            console.log(temp, "temp");
            // 带入姓名 用户id  部门id 所属部门 所属岗位
            this.form.deptId = temp.deptId;
            this.form.userId = temp.userId;
            this.form.orgId = temp.orgId;
            this.form.postId = temp.postId;

            this.form.sex = temp.sex;
            this.form.staffType = temp.staffType;

            this.form.type = "1";
            this.$set(this.form, "realName", temp.realName);
        },
        showTableDialog() {
            this.showTableVision = true;
        },
        /** 查询【请填写功能名称】列表 */
        getList() {
            this.loading = true;
            getSalaryList(this.queryParams).then((response) => {
                this.leaveList = response.rows;
                this.total = response.total;

                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
            };
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.timeArr = [];
            this.queryParams.startDate = null;
            this.queryParams.endDate = null;
            this.queryParams.postName = null ;

            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新建按钮操作 */
        handleAdd() {
            this.reset();
            this.showOptions = false;
            this.open = true;
            this.title = "加班计费规则";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = { ...row };
            // const id = row.id || this.ids;
            this.showOptions = false;
            this.open = true;
            this.title = "加班计费编辑";
            // getLeave(id).then((response) => {
            //   this.form = response.data;
            //   this.showOptions = false;
            //   this.open = true;
            //   this.title = "修改【请填写功能名称】";
            // });
        },
        /** 查看按钮操作 */
        handleRead(row) {
            this.reset();

            this.form = { ...row };
            // const id = row.id || this.ids;
            this.showOptions = true;
            this.open = true;
            this.title = "加班计费查看";
            // getSalaryListByUserId(id).then((response) => {
            //   this.form = response.data;
            //   this.showOptions = true;
            //   this.open = true;
            //   this.title = "查看员工加班信息";
            // });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        this.form.type = 1;
                        this.form.lossSalary = Number(this.form.lossSalary);
                        this.form.postSalary = Number(this.form.postSalary);

                        if (
                            this.$store.getters.allDefectObj["HR-WEB-078"] == 0
                        ) {
                            this.open = false;
                            return;
                        }

                        updateSalary(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        this.form.type = 1;
                        this.form.lossSalary = Number(this.form.lossSalary);
                        this.form.postSalary = Number(this.form.postSalary);
                        addSalary(this.form).then((response) => {
                            this.$modal.msgSuccess("新建成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm("请确认是否删除该记录", "删除确认")
                .then(function () {
                    return deleteSalary({ id: ids });
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "back/leave/export",
                {
                    ...this.queryParams,
                },
                `leave_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
